/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.dailyinfo.smscbclient;

import com.elcom.config.ModuleConfig;
import com.elcom.dailyinfo.smscbclient.httpclient.SmscbHttpClient;
import com.elcom.dailyinfo.smscbclient.cbcrequest.CbcRequest;
import com.elcom.dailyinfo.smscbclient.cbcrequest.CbcRequestType;
import com.elcom.dailyinfo.smscbclient.cbcrequest.GetBscCellsRequest;
import com.elcom.dailyinfo.smscbclient.cbcrequest.GetBscsRequest;
import com.elcom.dailyinfo.smscbclient.cbcrequest.GetMessageInfoRequest;
import com.elcom.dailyinfo.smscbclient.cbcrequest.GetMessageStatusRequest;
import com.elcom.dailyinfo.smscbclient.cbcrequest.KillMessageRequest;
import com.elcom.dailyinfo.smscbclient.cbcrequest.SendMessageRequest;
import com.elcom.dailyinfo.smscbclient.cbcrequest.UpdateMessageRequest;
import com.elcom.emocbc.cbcgateway.smscbresponse.BroadcastState;
import com.elcom.emocbc.cbcgateway.smscbresponse.GetMessageInfoResponseParser;
import com.elcom.emocbc.cbcgateway.smscbresponse.GetMessageStatusResponseParser;
import com.elcom.emocbc.cbcgateway.smscbresponse.SendMessageResponse;
import com.elcom.emocbc.cbcgateway.smscbresponse.SendMessageResponseParser;
import com.elcom.emocbc.dbmapping.persistence.BscBroadcastResultPersistance;
import com.elcom.emocbc.dbmapping.persistence.DbAccess;
import com.elcom.emocbc.dbmapping.persistence.SmscbMessageResultPersistance;
import com.elcom.emocbc.dbmapping.tables.pojos.BscBroadcastResult;
import com.elcom.emocbc.dbmapping.tables.pojos.SmscbMessageResult;
import com.elcom.emocbc.mongodb.CellBroadcastResult;
import com.elcom.emocbc.mongodb.CellBroadcastResultDao;
import com.elcom.emocbc.mongodb.MongoDbAccess;
import com.elcom.util.Constant;
import com.google.code.morphia.Datastore;
import java.awt.Cursor;
import java.awt.event.ItemEvent;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.jconfig.Configuration;
import org.jconfig.ConfigurationManager;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.elcom.dailyinfo.smscbclient//SmscbClient//EN",
        autostore = false)
@TopComponent.Description(
        preferredID = "SmscbClientTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = true)
@ActionID(category = "Window", id = "com.elcom.dailyinfo.smscbclient.SmscbClientTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_SmscbClientAction",
        preferredID = "SmscbClientTopComponent")
@Messages({
    "CTL_SmscbClientAction=SmscbClient",
    "CTL_SmscbClientTopComponent=SmscbClient Window",
    "HINT_SmscbClientTopComponent=This is a SmscbClient window"
})
public final class SmscbClientTopComponent extends TopComponent {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private String username = "";
    private String password = "";
    private String messageId = "";
    private String smscbServerUri = "";
    private String httpConnectionStatus = "";
    private String functionName = "sendmessage";
    private CbcRequest smscbCommand;
    private GetBscsRequest getBscsCommand = new GetBscsRequest();
    private GetBscCellsRequest getBscCellsCommand = new GetBscCellsRequest();
    private SendMessageRequest sendMessageCommand = new SendMessageRequest();
    private UpdateMessageRequest updateMessageRequest = new UpdateMessageRequest();
    private KillMessageRequest killMessageRequest = new KillMessageRequest();
    private GetMessageInfoRequest getMessageInfoRequest = new GetMessageInfoRequest();
    private GetMessageStatusRequest getMessageStatusRequest = new GetMessageStatusRequest();
    private DefaultComboBoxModel dcbmFunctionName;
    private SmscbMessageResult smscbMessage;

    public SmscbClientTopComponent() {
        try {
            File file = new File(Constant.CONFIG_FOLDER);
            if (!file.exists()) {
                file.mkdirs();
            }

            ModuleConfig jConfig = new ModuleConfig(Constant.SYS_CONFIG_NAME);
            try {
                jConfig.reloadConfig(Constant.CONFIG_FOLDER, Constant.CONFIG_FILE_NAME);
                logger.info("Done reload config");
            } catch (Exception ex) {
                logger.error("", ex);
            }

            setupDatabaseAccess();
            logger.info("Done setup dbaccess");
            setupMongoDatastoreAccess();
            logger.info("Done setup mongo access");
        } catch (Exception e) {
            logger.info("DBAEx");
        }

        initComponents();
        dcbmFunctionName = new DefaultComboBoxModel();
        dcbmFunctionName.addElement("sendmessage");
        dcbmFunctionName.addElement("getmessageinfo");
        dcbmFunctionName.addElement("getmessagestatus");
        dcbmFunctionName.addElement("getbscs");
        dcbmFunctionName.addElement("getbsccells");
        dcbmFunctionName.addElement("killmessage");
        dcbmFunctionName.addElement("updatemessage");
        cbxFunctionName.setModel(dcbmFunctionName);
        cbxFunctionName.setSelectedIndex(0);
        functionName = cbxFunctionName.getSelectedItem().toString();

        setName(Bundle.CTL_SmscbClientTopComponent());
        setToolTipText(Bundle.HINT_SmscbClientTopComponent());
        fillForm();
    }

    private void extractForm() {
        smscbServerUri = txtUri.getText().trim();
        username = txtUsername.getText().trim();
        password = txtPassword.getText().trim();
        messageId = txtMsgId.getText().trim();

        functionName = (String) cbxFunctionName.getSelectedItem();
        if (functionName.equals(CbcRequestType.GET_BSCS)) {
            getBscsCommand = new GetBscsRequest();
            getBscsCommand.setUsername(username);
            getBscsCommand.setPassword(password);
            smscbCommand = getBscsCommand;
        } else if (functionName.equals(CbcRequestType.GET_BSC_CELLS)) {
            getBscCellsCommand = new GetBscCellsRequest();
            getBscCellsCommand.setUsername(username);
            getBscCellsCommand.setPassword(password);
            getBscCellsCommand.setBscId(txtBscId.getText().trim());
            smscbCommand = getBscCellsCommand;
        } else if (functionName.equals(CbcRequestType.SEND_MESSAGE)) {
            sendMessageCommand = new SendMessageRequest();
            sendMessageCommand.setUsername(username);
            sendMessageCommand.setPassword(password);
            sendMessageCommand.setMessageId(messageId);
            sendMessageCommand.setBscList(txtBscList.getText().trim());
            sendMessageCommand.setCellList(txtCellIdList.getText().trim());
            sendMessageCommand.setData(txtData.getText().trim());
            sendMessageCommand.setDcs(txtDcs.getText().trim());
            sendMessageCommand.setDuration(Long.valueOf(txtDuration.getText() == null ? "-1" : txtDuration.getText().trim()));
            sendMessageCommand.setEncoding(txtEncoding.getText().trim());
            sendMessageCommand.setRepetitionRate(Integer.valueOf(txtRepetationRate.getText() == null ? "-1" : txtRepetationRate.getText().trim()));
            sendMessageCommand.setWaitToBroadcast(Long.valueOf(txtWaitToBroadcast.getText() == null ? "-1" : txtWaitToBroadcast.getText().trim()));
            smscbCommand = sendMessageCommand;
        } else if (functionName.equals(CbcRequestType.UPDATE_MESSAGE)) {
            updateMessageRequest = new UpdateMessageRequest();
            updateMessageRequest.setUsername(username);
            updateMessageRequest.setPassword(password);
            updateMessageRequest.setMessageId(messageId);
            updateMessageRequest.setData(txtData.getText().trim());
            smscbCommand = updateMessageRequest;
        } else if (functionName.equals(CbcRequestType.KILL_MESSAGE)) {
            killMessageRequest = new KillMessageRequest();
            killMessageRequest.setUsername(username);
            killMessageRequest.setPassword(password);
            killMessageRequest.setMessageId(messageId);
            smscbCommand = killMessageRequest;
        } else if (functionName.equals(CbcRequestType.GET_MESSAGE_INFO)) {
            getMessageInfoRequest = new GetMessageInfoRequest();
            getMessageInfoRequest.setUsername(username);
            getMessageInfoRequest.setPassword(password);
            getMessageInfoRequest.setMessageId(messageId);
            smscbCommand = getMessageInfoRequest;
        } else if (functionName.equals(CbcRequestType.GET_MESSAGE_STATUS)) {
            getMessageStatusRequest = new GetMessageStatusRequest();
            getMessageStatusRequest.setUsername(username);
            getMessageStatusRequest.setPassword(password);
            getMessageStatusRequest.setMessageId(messageId);
            smscbCommand = getMessageStatusRequest;
        }
    }

    private void fillForm() {
        txtBscId.setText(getBscCellsCommand.getBscId());
        txtBscList.setText(sendMessageCommand.getBscList());
        txtCellIdList.setText(sendMessageCommand.getCellList());
        txtData.setText(sendMessageCommand.getData());
        txtDcs.setText(sendMessageCommand.getDcs());
        txtDuration.setText(String.valueOf(sendMessageCommand.getDuration()));
        txtEncoding.setText(sendMessageCommand.getEncoding());
        txtMsgId.setText(sendMessageCommand.getMessageId());
        txtPassword.setText(password);
        txtRepetationRate.setText(String.valueOf(sendMessageCommand.getRepetitionRate()));
        txtUri.setText(smscbServerUri);
        txtUsername.setText(username);
        txtWaitToBroadcast.setText(String.valueOf(sendMessageCommand.getWaitToBroadcast()));
    }

    private void toggleComponents() {
        functionName = (String) cbxFunctionName.getSelectedItem();
        if (functionName.equals(CbcRequestType.GET_BSCS)) {
            txtBscId.setEnabled(false);
            txtBscList.setEnabled(false);
            txtCellIdList.setEnabled(false);
            txtData.setEnabled(false);
            txtDcs.setEnabled(false);
            txtDuration.setEnabled(false);
            txtEncoding.setEnabled(false);
            txtMsgId.setEnabled(false);
            txtRepetationRate.setEnabled(false);
            txtWaitToBroadcast.setEnabled(false);
        } else if (functionName.equals(CbcRequestType.GET_BSC_CELLS)) {
            txtBscId.setEnabled(true);
            txtBscList.setEnabled(false);
            txtCellIdList.setEnabled(false);
            txtData.setEnabled(false);
            txtDcs.setEnabled(false);
            txtDuration.setEnabled(false);
            txtEncoding.setEnabled(false);
            txtMsgId.setEnabled(false);
            txtRepetationRate.setEnabled(false);
            txtWaitToBroadcast.setEnabled(false);
        } else if (functionName.equals(CbcRequestType.SEND_MESSAGE)) {
            txtBscId.setEnabled(false);
            txtBscList.setEnabled(true);
            txtCellIdList.setEnabled(true);
            txtData.setEnabled(true);
            txtDcs.setEnabled(true);
            txtDuration.setEnabled(true);
            txtEncoding.setEnabled(true);
            txtMsgId.setEnabled(true);
            txtRepetationRate.setEnabled(true);
            txtWaitToBroadcast.setEnabled(true);
        } else if (functionName.equals(CbcRequestType.UPDATE_MESSAGE)) {
            txtBscId.setEnabled(false);
            txtBscList.setEnabled(false);
            txtCellIdList.setEnabled(false);
            txtData.setEnabled(true);
            txtDcs.setEnabled(false);
            txtDuration.setEnabled(false);
            txtEncoding.setEnabled(false);
            txtMsgId.setEnabled(true);
            txtRepetationRate.setEnabled(false);
            txtWaitToBroadcast.setEnabled(false);
        } else if (functionName.equals(CbcRequestType.KILL_MESSAGE)) {
            txtBscId.setEnabled(false);
            txtBscList.setEnabled(false);
            txtCellIdList.setEnabled(false);
            txtData.setEnabled(false);
            txtDcs.setEnabled(false);
            txtDuration.setEnabled(false);
            txtEncoding.setEnabled(false);
            txtMsgId.setEnabled(true);
            txtRepetationRate.setEnabled(false);
            txtWaitToBroadcast.setEnabled(false);
        } else if (functionName.equals(CbcRequestType.GET_MESSAGE_INFO)) {
            txtBscId.setEnabled(false);
            txtBscList.setEnabled(false);
            txtCellIdList.setEnabled(false);
            txtData.setEnabled(false);
            txtDcs.setEnabled(false);
            txtDuration.setEnabled(false);
            txtEncoding.setEnabled(false);
            txtMsgId.setEnabled(true);
            txtRepetationRate.setEnabled(false);
            txtWaitToBroadcast.setEnabled(false);
        } else if (functionName.equals(CbcRequestType.GET_MESSAGE_STATUS)) {
            txtBscId.setEnabled(false);
            txtBscList.setEnabled(false);
            txtCellIdList.setEnabled(false);
            txtData.setEnabled(false);
            txtDcs.setEnabled(false);
            txtDuration.setEnabled(false);
            txtEncoding.setEnabled(false);
            txtMsgId.setEnabled(true);
            txtRepetationRate.setEnabled(false);
            txtWaitToBroadcast.setEnabled(false);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtUri = new javax.swing.JTextField();
        btnConnect = new javax.swing.JToggleButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        cbxFunctionName = new javax.swing.JComboBox();
        btnExecute = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        txtBscId = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtDuration = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        txtWaitToBroadcast = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        txtRepetationRate = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        txtBscList = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        txtCellIdList = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        txtMsgId = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtData = new javax.swing.JTextArea();
        txtDcs = new javax.swing.JTextField();
        txtEncoding = new javax.swing.JTextField();
        btnBrowse = new javax.swing.JButton();
        txtFilePath = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JTextField();
        jProgressBar = new javax.swing.JProgressBar();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jPanel1.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel1.text")); // NOI18N

        txtUri.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtUri.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(btnConnect, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.btnConnect.text")); // NOI18N
        btnConnect.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                btnConnectItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtUri)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnConnect)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUri, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConnect))
                .addGap(1, 1, 1))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jPanel2.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel4.text")); // NOI18N

        cbxFunctionName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "sendmessage", "getbscs", "getbsccells" }));
        cbxFunctionName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbxFunctionNameActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(btnExecute, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.btnExecute.text")); // NOI18N
        btnExecute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExecuteActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel5.text")); // NOI18N

        txtBscId.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtBscId.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel8, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel8.text")); // NOI18N

        txtDuration.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtDuration.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel9, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel9.text")); // NOI18N

        txtWaitToBroadcast.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtWaitToBroadcast.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel10, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel10.text")); // NOI18N

        txtRepetationRate.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtRepetationRate.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel11, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel11.text")); // NOI18N

        txtBscList.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtBscList.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel12, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel12.text")); // NOI18N

        txtCellIdList.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtCellIdList.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel13, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel13.text")); // NOI18N

        txtMsgId.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtMsgId.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel14, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel14.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel15, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel15.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel16, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel16.text")); // NOI18N

        txtData.setColumns(20);
        txtData.setLineWrap(true);
        txtData.setRows(5);
        jScrollPane1.setViewportView(txtData);

        txtDcs.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtDcs.text")); // NOI18N

        txtEncoding.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtEncoding.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(btnBrowse, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.btnBrowse.text")); // NOI18N
        btnBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBrowseActionPerformed(evt);
            }
        });

        txtFilePath.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtFilePath.text")); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel9)
                    .addComponent(jLabel10)
                    .addComponent(jLabel11)
                    .addComponent(jLabel12)
                    .addComponent(jLabel13)
                    .addComponent(jLabel14)
                    .addComponent(jLabel15)
                    .addComponent(jLabel16)
                    .addComponent(jLabel8)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(txtFilePath)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnBrowse))
                    .addComponent(txtBscList)
                    .addComponent(txtCellIdList)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtWaitToBroadcast, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
                            .addComponent(txtRepetationRate)
                            .addComponent(txtDuration)
                            .addComponent(txtBscId)
                            .addComponent(txtMsgId, javax.swing.GroupLayout.DEFAULT_SIZE, 71, Short.MAX_VALUE)
                            .addComponent(txtDcs)
                            .addComponent(txtEncoding))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtBscId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtDuration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(txtWaitToBroadcast, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(txtRepetationRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(txtBscList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(txtCellIdList, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(txtMsgId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel14)
                    .addComponent(txtDcs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(txtEncoding, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel16)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBrowse)
                    .addComponent(txtFilePath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel6.text")); // NOI18N

        txtUsername.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtUsername.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.jLabel7.text")); // NOI18N

        txtPassword.setText(org.openide.util.NbBundle.getMessage(SmscbClientTopComponent.class, "SmscbClientTopComponent.txtPassword.text")); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbxFunctionName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnExecute)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cbxFunctionName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExecute)
                    .addComponent(jLabel6)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(429, 429, 429)
                .addComponent(jProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cbxFunctionNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxFunctionNameActionPerformed
        toggleComponents();
    }//GEN-LAST:event_cbxFunctionNameActionPerformed

    private void btnExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExecuteActionPerformed
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        jProgressBar.setIndeterminate(true);
        extractForm();

        try {
            SmscbHttpClient httpClient = SmscbHttpClient.getInstance(smscbServerUri);
            String xmlResponse = httpClient.send(smscbCommand);
            try {
                saveResult(xmlResponse);
            } catch (Exception ex) {
                logger.error("", ex);
            }
        } catch (Exception ex) {
            logger.warn("", ex);
        }

        fillForm();
        this.setCursor(Cursor.getDefaultCursor());
        jProgressBar.setIndeterminate(false);

    }//GEN-LAST:event_btnExecuteActionPerformed

    private void btnConnectItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_btnConnectItemStateChanged
        smscbServerUri = txtUri.getText().trim();
        int state = evt.getStateChange();
        if (state == ItemEvent.SELECTED) {
            btnConnect.setText("Disconnect");
            SmscbHttpClient.getInstance(smscbServerUri).connect();
        } else {
            btnConnect.setText("Connect");
            SmscbHttpClient httpClient = SmscbHttpClient.getInstance(smscbServerUri);
            try {
                httpClient.shutdownConnection();
            } catch (Exception ex) {
                logger.error("", ex);
            }
        }
    }//GEN-LAST:event_btnConnectItemStateChanged

    private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowseActionPerformed
        JFileChooser jFileChooser = new JFileChooser();
        String path = txtFilePath.getText().trim();
        if (path != null) {
            File currentDir = new File(path);
            if (!currentDir.isDirectory()) {
                currentDir = new File(FilenameUtils.getFullPathNoEndSeparator(path));
            }

            jFileChooser.setCurrentDirectory(currentDir);
        }
        jFileChooser.showOpenDialog(this);

        File selectedFile = jFileChooser.getSelectedFile();
        if (selectedFile.isFile()) {
            txtFilePath.setText(selectedFile.getPath());
            try {
                byte[] byteArray = FileUtils.readFileToByteArray(selectedFile);
                String hexString = convertBinary2Hexadecimal(byteArray);
                txtData.setText(hexString.substring(12));
            } catch (IOException ex) {
                logger.error("", ex);
            }
        }

    }//GEN-LAST:event_btnBrowseActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBrowse;
    private javax.swing.JToggleButton btnConnect;
    private javax.swing.JButton btnExecute;
    private javax.swing.JComboBox cbxFunctionName;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JProgressBar jProgressBar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField txtBscId;
    private javax.swing.JTextField txtBscList;
    private javax.swing.JTextField txtCellIdList;
    private javax.swing.JTextArea txtData;
    private javax.swing.JTextField txtDcs;
    private javax.swing.JTextField txtDuration;
    private javax.swing.JTextField txtEncoding;
    private javax.swing.JTextField txtFilePath;
    private javax.swing.JTextField txtMsgId;
    private javax.swing.JTextField txtPassword;
    private javax.swing.JTextField txtRepetationRate;
    private javax.swing.JTextField txtUri;
    private javax.swing.JTextField txtUsername;
    private javax.swing.JTextField txtWaitToBroadcast;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    public String getSmscbServerUri() {
        return smscbServerUri;
    }

    public void setSmscbServerUri(String smscbServerUri) {
        this.smscbServerUri = smscbServerUri;
    }

    public String getHttpConnectionStatus() {
        return httpConnectionStatus;
    }

    public void setHttpConnectionStatus(String httpConnectionStatus) {
        this.httpConnectionStatus = httpConnectionStatus;
    }

    public GetBscsRequest getGetBscsCommand() {
        return getBscsCommand;
    }

    public void setGetBscsCommand(GetBscsRequest getBscsCommand) {
        this.getBscsCommand = getBscsCommand;
    }

    public GetBscCellsRequest getGetBscCellsCommand() {
        return getBscCellsCommand;
    }

    public void setGetBscCellsCommand(GetBscCellsRequest getBscCellsCommand) {
        this.getBscCellsCommand = getBscCellsCommand;
    }

    public SendMessageRequest getSendMessageCommand() {
        return sendMessageCommand;
    }

    public void setSendMessageCommand(SendMessageRequest sendMessageCommand) {
        this.sendMessageCommand = sendMessageCommand;
    }

    public String getMessageId() {
        return messageId;
    }

    public void setMessageId(String messageId) {
        this.messageId = messageId;
    }

    private String convertBinary2Hexadecimal(byte[] binary) {
        final String HEX_STRING = "0123456789ABCDEF";
        StringBuilder buf = new StringBuilder();
        int block;

        for (int i = 0; i < binary.length; i++) {
            block = binary[i] & 0xFF;
            buf.append(HEX_STRING.charAt(block >> 4));
            buf.append(HEX_STRING.charAt(binary[i] & 0x0F));
        }

        return buf.toString();
    }

    private void setupDatabaseAccess() {
        Configuration config = ConfigurationManager.getConfiguration(Constant.SYS_CONFIG_NAME);
        DbAccess.getInstance().setProperties(config.getProperties("jdbc"));
        logger.info("Done setup Database access");
    }

    private void setupMongoDatastoreAccess() {
        Configuration config = ConfigurationManager.getConfiguration(Constant.SYS_CONFIG_NAME);
        Properties properties = config.getProperties("mongodb");
        try {
            MongoDbAccess.getInstance().setupDatastore(properties);
            logger.info("Done setup MongoDatastore access");
        } catch (UnknownHostException ex) {
            logger.error("", ex);
        }
    }

    private void saveResult(String xmlResponse) throws Exception {
        SmscbMessageResultPersistance smscbMessageResultDao = new SmscbMessageResultPersistance();
        if (smscbCommand instanceof SendMessageRequest) {
            SendMessageResponse response = SendMessageResponseParser.parse(xmlResponse);
            SendMessageRequest request = (SendMessageRequest) smscbCommand;
            smscbMessage = new SmscbMessageResult();
            smscbMessage.setMsgSeqId(UUID.randomUUID().toString());
            smscbMessage.setBroadcastChannel(Integer.valueOf(request.getMessageId()));
            smscbMessage.setData(request.getData());
            smscbMessage.setDcs(request.getDcs());
            smscbMessage.setDuration(request.getDuration());
            smscbMessage.setEncodingRule(request.getEncoding());
            smscbMessage.setWaitToBroadcast(request.getWaitToBroadcast());
            smscbMessage.setBroadcastState("To be submitted");
            smscbMessage.setBroadcastStateCode(0);
            smscbMessage.setLastUpdatedTime(new Timestamp(new Date().getTime()));
            smscbMessage.setSummittedTime(new Timestamp(new Date().getTime()));
            smscbMessage.setRepetitionRate(request.getRepetitionRate());
            smscbMessage.setMessageId(response.getMessageId());
            smscbMessage.setTotalCells(0);
            smscbMessage.setSuccessCells(0);
            smscbMessage.setFailureCells(0);
            smscbMessage.setPendingCells(0);
            smscbMessageResultDao.insert(smscbMessage);

        } else if (smscbCommand instanceof GetMessageInfoRequest) {
            GetMessageInfoRequest request = (GetMessageInfoRequest) smscbCommand;
            SmscbMessageResult smr = GetMessageInfoResponseParser.parse(xmlResponse);
            smscbMessage = smscbMessageResultDao.fetchByMessageId(request.getMessageId()).get(0);
            smscbMessage.setBroadcastState(smr.getBroadcastState());
            smscbMessage.setStartTime(smr.getStartTime());
            smscbMessage.setEndTime(smr.getEndTime());
            smscbMessage.setLastUpdatedTime(new Timestamp(new Date().getTime()));
            smscbMessageResultDao.update(smscbMessage);
        } else if (smscbCommand instanceof GetMessageStatusRequest) {
            GetMessageStatusRequest request = (GetMessageStatusRequest) smscbCommand;
            List<CellBroadcastResult> cellBroadcastResults = GetMessageStatusResponseParser.parse(xmlResponse);
            smscbMessage = smscbMessageResultDao.fetchByMessageId(request.getMessageId()).get(0);
            updateBroadcastResult(cellBroadcastResults);
        }
    }

    private void updateBroadcastResult(List<CellBroadcastResult> cellBroadcastResults) throws UnknownHostException {
        CellBroadcastResultDao dao = null;
        try {
            Datastore ds = MongoDbAccess.getInstance().getDatastore();
            dao = new CellBroadcastResultDao(ds);
        } catch (Exception ex) {
            logger.error("Error connecting to Mongodb", ex);
        }
        logger.trace("Saving CellBroadcastResults");
        int successCells = 0;
        int failedCells = 0;

        Map<String, BscBroadcastResult> bscMap = new HashMap<String, BscBroadcastResult>();
        for (CellBroadcastResult cellBroadcastResult : cellBroadcastResults) {
            try {
                //bsc
                String bscId = cellBroadcastResult.getBscId();
                BscBroadcastResult bscBroadcastResult;
                if (bscMap.containsKey(bscId)) {
                    bscBroadcastResult = bscMap.get(bscId);

                } else {
                    bscBroadcastResult = new BscBroadcastResult();
                    bscBroadcastResult.setBroadcastMessageId(smscbMessage.getMessageId());
                    bscBroadcastResult.setBroadcastState(BroadcastState.ENDED);
                    bscBroadcastResult.setBscId(bscId);
                    bscBroadcastResult.setCbmId(smscbMessage.getCbmId());
                    bscBroadcastResult.setFailureCells(0);
                    bscBroadcastResult.setId(UUID.randomUUID().toString());
                    bscBroadcastResult.setLastUpdatedTime(new Timestamp(new Date().getTime()));
                    bscBroadcastResult.setMsgSeqId(smscbMessage.getMsgSeqId());
                    bscBroadcastResult.setPendingCells(0);
//                    bscBroadcastResult.setRegion(smscbMessage.getMessageId());
                    bscBroadcastResult.setScheduleId(smscbMessage.getScheduleId());
                    bscBroadcastResult.setBroadcastTime(smscbMessage.getSummittedTime());
                    bscBroadcastResult.setSuccessCells(0);
                    bscBroadcastResult.setTotalCells(0);
                    bscBroadcastResult.setZoneId(smscbMessage.getZoneId());

                    bscMap.put(bscId, bscBroadcastResult);
                }

                if (cellBroadcastResult.getBroadcastFailed()) {
                    failedCells++;
                    bscBroadcastResult.setFailureCells(bscBroadcastResult.getFailureCells() + 1);
                    bscBroadcastResult.setTotalCells(bscBroadcastResult.getTotalCells() + 1);
                } else {
                    successCells++;
                    bscBroadcastResult.setSuccessCells(bscBroadcastResult.getSuccessCells() + 1);
                    bscBroadcastResult.setTotalCells(bscBroadcastResult.getTotalCells() + 1);
                }
                cellBroadcastResult.setCbmId(smscbMessage.getCbmId());
                cellBroadcastResult.setMsgSeqId(smscbMessage.getMsgSeqId());
                cellBroadcastResult.setScheduleId(smscbMessage.getScheduleId());
                cellBroadcastResult.setZoneId(smscbMessage.getZoneId().toString());
                cellBroadcastResult.setBroadcastTime(smscbMessage.getSummittedTime());
                if (dao != null) {
                    dao.save(cellBroadcastResult);
                }

            } catch (Exception ex) {
                logger.error("Error saving CellBroadcastResult. Cell: {}, MsgId: {}", new Object[]{cellBroadcastResult.getCellId(), smscbMessage.getMessageId()});
            }
        }
        logger.trace("Saved CellBroadcastResults");


        Collection<BscBroadcastResult> bscBroadcastResults = bscMap.values();
        try {
            BscBroadcastResultPersistance bscBroadcastResultDao = new BscBroadcastResultPersistance();
            for (BscBroadcastResult bscBroadcastResult : bscBroadcastResults) {
                bscBroadcastResultDao.insert(bscBroadcastResult);
                logger.info("Save BscBroadcastResults. MsgId: {}, bscId {}", new Object[]{smscbMessage.getMessageId(), bscBroadcastResult.getBscId()});
            }
        } catch (SQLException ex) {
            logger.error("Error saving BscBroadcastResults. MsgId: {}", new Object[]{smscbMessage.getMessageId(), ex});
        }


        int totalCells = cellBroadcastResults.size();
        int pendingCells = totalCells - successCells - failedCells;
//        try {
//            String scheduleId = smscbMessage.getScheduleId();
//            ProgramBroadcastResultPersistance resultDao = new ProgramBroadcastResultPersistance();
//            ProgramBroadcastResult result = resultDao.fetchOneByScheduleId(scheduleId);
//            result.setFailureCells(result.getFailureCells() + failedCells);
//            result.setSuccessCells(result.getSuccessCells() + successCells);
//            result.setTotalCells(result.getTotalCells() + totalCells);
//            result.setPendingCells(result.getPendingCells() + pendingCells);
//            result.setLastUpdatedTime(new Timestamp(new Date().getTime()));
//            result.setBroadcastState(BroadcastState.ENDED);
//            resultDao.update(result);
//            logger.debug("Updated ProgramBroadcastResult (scheduleId: {})", scheduleId);
//        } catch (SQLException ex) {
//            logger.error("Error update ProgramBroadcastResult (scheduleId: {})", scheduleId, ex);
//        }


        try {
            smscbMessage.setFailureCells(failedCells);
            smscbMessage.setSuccessCells(successCells);
            smscbMessage.setTotalCells(totalCells);
            smscbMessage.setPendingCells(pendingCells);
            smscbMessage.setLastUpdatedTime(new Timestamp(new Date().getTime()));
            smscbMessage.setBroadcastState(BroadcastState.ENDED);
            new SmscbMessageResultPersistance().update(smscbMessage);
            logger.debug("Updated SmscbMessageResult (msgId: {})", smscbMessage.getMessageId());
        } catch (SQLException ex) {
            logger.error("Error updating SmscbMessageResult (msgId: {})", smscbMessage.getMessageId(), ex);
        }
    }
}
